package com.sgcc.ln.pmos.e_ln_mall.activity;


import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.sgcc.ln.pmos.common.base.MvpBaseActivity;
import com.sgcc.ln.pmos.common.bean.ComputationBean;
import com.sgcc.ln.pmos.common.bean.EventCenter;
import com.sgcc.ln.pmos.common.http.MvcNetCallback;
import com.sgcc.ln.pmos.common.utils.ArguConstant;
import com.sgcc.ln.pmos.common.view.LineChartView;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.e_ln_mall.adapter.HistoryCurveDataAdapter;
import com.sgcc.ln.pmos.e_ln_mall.bean.CurveHistoryDataBackBean;
import com.sgcc.ln.pmos.e_ln_mall.bean.TabEntity;
import com.sgcc.ln.pmos.e_ln_mall.contract.ElectricityProportionContract;
import com.sgcc.ln.pmos.e_ln_mall.presenter.ElectricityProportionPresenter;
import com.sgcc.ln.pmos.e_ln_mall.presenter.PredictPriceHttp;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author ChaoAJ
 * @describe 设置电量比例
 * @time 2022/9/5 11:10
 */
public class ElectricityProportionActivity extends MvpBaseActivity<ElectricityProportionPresenter> implements ElectricityProportionContract.View {

    private TitleBar tbElectricityProportionTitle;
    private CommonTabLayout ctlTabLayout;
    private CommonTabLayout ctlTabLayout1;
    private TextView tvType;
    private RelativeLayout rlCurveType1;
    private TextView tvCurveType1;
    private LinearLayout llLineChart1;
    private RelativeLayout rlCurveType2;
    private TextView tvCurveType2;
    private LinearLayout llLineChart2;
    private RelativeLayout rlCurveType3;
    private TextView tvCurveType3;
    private RecyclerView rvLineChart3;
    private TextView tvRvHisNullView;
    private EditText etDeviationPowerRatio;
    private TextView tvNext;
    private LinearLayout llElectricityCurveLayout;
    private LinearLayout llDeviationCurveLayout;

    private LinearLayout llDeviationRatioLayout;
    private String[] curveTexts = null;
    private String[] deviationCurveTexts = null;

    private int priceType = 1; //1  历史价格 2 综合价格

    private boolean isSelectHistory = false;

    private List<List<String>> curveDataList = new ArrayList<>();//电量曲线数据

    private List<List<String>> deviationCurveDataList = new ArrayList<>();//偏差电量曲线数据


    private ArrayList<String> curveList = new ArrayList<>();//传递的数据 电量曲线数据
    private ArrayList<String> deviationCurveList = new ArrayList<>();//传递的数据 偏差电量曲线数据

    private int pageType;// 0分时 约定电量  1 分时 不约定电量  2不分时 约定电量  3 不分时 不约定电量

    private ArrayList<String> packageId;

    private String calDate;
    private int queryHisCurveDataPosition = 0;
    private String[] hisCurveDates;//历史用电量曲线 历史日期

    private String[] hisCurvePriceDates;//历史价格曲线 日期
    private String[] synthesisPriceDates;//综合价格 日期


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_electricity_proportion;
    }


    @Override
    protected void initViews() {
        super.initViews();
        Intent intent = getIntent();
        pageType = intent.getIntExtra("pageType", 0);
        packageId = intent.getStringArrayListExtra("packageId");
        tbElectricityProportionTitle = findViewById(R.id.tb_electricityProportion_title);
        tbElectricityProportionTitle.setTitle("设置电量比例");
        tbElectricityProportionTitle.setRightIcon(R.mipmap.go_main, view -> goMainActivity());
        ctlTabLayout = findViewById(R.id.ctlTabLayout);
        ctlTabLayout1 = findViewById(R.id.ctlTabLayout1);
        tvType = findViewById(R.id.tvType);
        rlCurveType1 = findViewById(R.id.rlCurveType1);
        tvCurveType1 = findViewById(R.id.tvCurveType1);
        llLineChart1 = findViewById(R.id.llLineChart1);
        rlCurveType2 = findViewById(R.id.rlCurveType2);
        tvCurveType2 = findViewById(R.id.tvCurveType2);
        llLineChart2 = findViewById(R.id.llLineChart2);
        rlCurveType3 = findViewById(R.id.rlCurveType3);
        tvCurveType3 = findViewById(R.id.tvCurveType3);
        rvLineChart3 = findViewById(R.id.rvLineChart3);
        tvRvHisNullView = findViewById(R.id.tvRvHisNullView);
        etDeviationPowerRatio = findViewById(R.id.etDeviationPowerRatio);
        llElectricityCurveLayout = findViewById(R.id.llElectricityCurveLayout);
        llDeviationCurveLayout = findViewById(R.id.llDeviationCurveLayout);

        llDeviationRatioLayout = findViewById(R.id.llDeviationRatioLayout);
        tvNext = findViewById(R.id.tvNext);

        if (pageType == 0) {
            llElectricityCurveLayout.setVisibility(View.VISIBLE);
            llDeviationCurveLayout.setVisibility(View.VISIBLE);
            llDeviationRatioLayout.setVisibility(View.GONE);
            tvNext.setText("下一步");

        } else if (pageType == 1) {
            llElectricityCurveLayout.setVisibility(View.VISIBLE);
            llDeviationCurveLayout.setVisibility(View.GONE);
            llDeviationRatioLayout.setVisibility(View.GONE);
            tvNext.setText("下一步");

        } else if (pageType == 2) {
            llDeviationRatioLayout.setVisibility(View.VISIBLE);
            llElectricityCurveLayout.setVisibility(View.GONE);
            llDeviationCurveLayout.setVisibility(View.GONE);

            tvNext.setText("计算预估价格");
        } else if (pageType == 3) {

            llDeviationRatioLayout.setVisibility(View.GONE);
            llElectricityCurveLayout.setVisibility(View.GONE);
            llDeviationCurveLayout.setVisibility(View.GONE);

            tvNext.setText("计算预估价格");
        }


    }


    @Override
    protected void initData() {
        super.initData();
        rvLineChart3.setLayoutManager(new LinearLayoutManager(mContext));


        ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
        tabEntities.add(new TabEntity("典型曲线"));
        tabEntities.add(new TabEntity("自定义曲线"));
        tabEntities.add(new TabEntity("历史用电量曲线"));
        ctlTabLayout.setTabData(tabEntities);

        ArrayList<CustomTabEntity> tabEntities1 = new ArrayList<>();
        tabEntities1.add(new TabEntity("历史价格"));
        tabEntities1.add(new TabEntity("综合价格"));
        ctlTabLayout1.setTabData(tabEntities1);


        if (pageType == 0 || pageType == 1)
            mPresenter.getCurveData(true, 2);
        if (pageType == 0)
            mPresenter.getDeviationCurveData(true, 4);
        mPresenter.getHisCurvePriceDate();
        ctlTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                isSelectHistory = position == 2;
                if (position == 0) {
                    tvType.setText("请选择典型曲线：");
                    mPresenter.getCurveData(true, 2);
                }
                if (position == 1) {
                    tvType.setText("请选择自定义曲线：");
                    mPresenter.getDeviationCurveData(true, 3);
                }
                if (position == 2) {
                    tvType.setText("请选择历史日期：");
                    mPresenter.getHisCurveDate();
                }


            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        ctlTabLayout1.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 0) {
                    priceType = 1;
                    mPresenter.getHisCurvePriceDate();

                }
                if (position == 1) {
                    priceType = 2;
                    mPresenter.getSynthesisPriceDate();
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        rlCurveType1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSelectHistory) {
                    if (null == hisCurveDates)
                        return;
                    new XPopup.Builder(mContext)
                            .hasShadowBg(true)
                            .maxHeight((int) (ScreenUtils.getScreenHeight() * .5f))
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .asBottomList("请选择一项", hisCurveDates,
                                    new OnSelectListener() {
                                        @Override
                                        public void onSelect(int position, String text) {
                                            tvCurveType1.setText(text);
                                            mPresenter.getHisCurveData(true, text);
                                        }
                                    }).show();

                } else
                    showPopupView(0, curveTexts, tvCurveType1, llLineChart1, curveDataList);
            }
        });

        rlCurveType2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupView(1, deviationCurveTexts, tvCurveType2, llLineChart2, deviationCurveDataList);
            }
        });


        rlCurveType3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentTab = ctlTabLayout1.getCurrentTab();

                new XPopup.Builder(mContext)
                        .hasShadowBg(true)
                        .maxHeight((int) (ScreenUtils.getScreenHeight() * .5f))
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asBottomList("请选择一项", currentTab == 0 ? hisCurvePriceDates
                                        : synthesisPriceDates,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        tvCurveType3.setText(text);
                                        calDate = text;
                                        if (currentTab == 0) {
                                            mPresenter.getHistoryCurveData(true, text);
                                        } else {
                                            mPresenter.getSynthesisPriceData(true, text);
                                        }
                                    }
                                }).show();


            }
        });

        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pageType == 0 || pageType == 1) {
                    Intent intent = new Intent(mContext, ElectricityProportionDataActivity.class);
                    intent.putExtra("pageType", pageType);
                    intent.putExtra("priceType", priceType);
                    intent.putExtra("calDate", calDate);
                    intent.putStringArrayListExtra("curveList", curveList);
                    intent.putStringArrayListExtra("packageId", packageId);
                    intent.putStringArrayListExtra("deviationCurveList", deviationCurveList);
                    ActivityUtils.startActivity(intent);
                } else {
                    String deviationRatio = "";
                    if (pageType == 2) {
                        deviationRatio = etDeviationPowerRatio.getText().toString().trim();
                        if (TextUtils.isEmpty(deviationRatio)) {
                            ToastUtils.showShort("请输入偏差电量占约定电量比例");
                            return;
                        }
                    }

                    getPrice(deviationRatio);


                }


            }
        });

    }


    private void getPrice(String deviationRatio) {

        // subEnergyType        第一位 分时1不分时0，第二位 约定1不约定0

        String subEnergyType = "11";

        if (pageType == 2) {
            subEnergyType = "01";
        }
        if (pageType == 3) {
            subEnergyType = "00";
        }


        PredictPriceHttp.price(packageId, calDate, priceType, subEnergyType, deviationRatio, new ArrayList<>(),
                new ArrayList<>(), new ArrayList<>(), new MvcNetCallback<ComputationBean>() {
                    @Override
                    public void onResponse(ComputationBean response, int id) {
                        super.onResponse(response, id);
                        Object data = response.getData();
                        if (data instanceof Collection) {
                            List<ComputationBean.Bean> beanList = GsonUtils.fromJson(GsonUtils.toJson(data), new TypeToken<List<ComputationBean.Bean>>() {
                            }.getType());
                            EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_ESTIMATED_PRICE, beanList));
                            finish();
                        } else if (data instanceof String) {
                            ToastUtils.showShort((String) data);
                        }

                    }
                });
    }


    @Override
    protected ElectricityProportionPresenter createPresenter() {
        return new ElectricityProportionPresenter();
    }

    //电量曲线
    @Override
    public void queryCurveDataSuccess(Map<String, List<String>> maps) {
        setData(1, maps);
    }


    //历史用电量曲线 日期
    @Override
    public void queryHisCurveDateSuccess(List<String> dataList) {
        if (null != dataList && dataList.size() > 0) {
            hisCurveDates = dataList.toArray(new String[dataList.size()]);
            String text = hisCurveDates[0];
            tvCurveType1.setText(text);
            mPresenter.getHisCurveData(true, text);
        } else {
            tvCurveType1.setText("暂无数据");
            setNullView(llLineChart1);
        }
    }

    //历史用电量曲线
    @Override
    public void queryHisCurveDataSuccess(List<String> list) {
        setLineChart(llLineChart1, false, list);

    }

    //偏差电量曲线
    @Override
    public void queryDeviationCurveDataSuccess(Map<String, List<String>> maps) {
        setData(2, maps);
    }


    //历史价格 日期
    @Override
    public void queryHisCurveDatePriceSuccess(List<String> dataList) {
        if (null != dataList && dataList.size() > 0) {
            hisCurvePriceDates = dataList.toArray(new String[dataList.size()]);
            calDate = hisCurvePriceDates[0];
            tvCurveType3.setText(calDate);
            mPresenter.getHistoryCurveData(true, calDate);
        } else {
            tvCurveType3.setText("暂无数据");
        }


    }


    //历史价格 曲线
    @Override
    public void queryHistoryCurveDataSuccess(List<CurveHistoryDataBackBean> dataList) {
        tvRvHisNullView.setVisibility(null == dataList || dataList.size() == 0 ? View.VISIBLE : View.GONE);
        rvLineChart3.setAdapter(new HistoryCurveDataAdapter(dataList));
    }


    //综合价格日期
    @Override
    public void querySynthesisPriceDateSuccess(List<String> dataList) {
        if (null != dataList && dataList.size() > 0) {
            synthesisPriceDates = dataList.toArray(new String[dataList.size()]);
            calDate = synthesisPriceDates[0];
            tvCurveType3.setText(calDate);
            mPresenter.getSynthesisPriceData(true, calDate);
        } else {
            tvCurveType3.setText("暂无数据");
        }


    }


    //查询综合价格 曲线
    @Override
    public void querySynthesisPriceDataSuccess(List<CurveHistoryDataBackBean> dataList) {
        tvRvHisNullView.setVisibility(null == dataList || dataList.size() == 0
                ? View.VISIBLE : View.GONE);
        rvLineChart3.setAdapter(new HistoryCurveDataAdapter(dataList));
    }


    @Override
    public void queryFailed() {

    }


    private void setData(int type, Map<String, List<String>> maps) {
        if (null == maps || maps.size() == 0) {
            if (type == 1) {
                if (!isSelectHistory)
                    tvCurveType1.setText("暂无数据");
                setNullView(llLineChart1);
                curveTexts = null;
                curveDataList.clear();
            } else {
                tvCurveType2.setText("暂无数据");
                setNullView(llLineChart2);
                deviationCurveTexts = null;
                deviationCurveDataList.clear();
            }
            return;
        }
        if (type == 1)
            curveTexts = new String[maps.size()];
        if (type == 2)
            deviationCurveTexts = new String[maps.size()];
        int i = 0;
        for (String key : maps.keySet()) {
            if (type == 1) {
                curveTexts[i] = key;
                curveDataList.add(maps.get(key));
            }
            if (type == 2) {
                deviationCurveTexts[i] = key;
                deviationCurveDataList.add(maps.get(key));
            }
            i++;
        }
        if (type == 1) {//电量曲线
            if (null == curveTexts || null == curveDataList || curveDataList.size() == 0) {
                tvCurveType1.setText("暂无数据");
                setNullView(llLineChart1);
                curveTexts = null;
                curveDataList.clear();
                return;
            }
            String string = curveTexts[0];
            tvCurveType1.setText(string);
            List<String> list = curveDataList.get(0);
            curveList.clear();
            curveList.addAll(list);
            setLineChart(llLineChart1, true, list);

        } else if (type == 2) {//偏差电量曲线
            if (null == deviationCurveTexts || null == deviationCurveDataList || deviationCurveDataList.size() == 0) {
                tvCurveType2.setText("暂无数据");
                setNullView(llLineChart2);
                deviationCurveTexts = null;
                deviationCurveDataList.clear();
                return;
            }
            String string = deviationCurveTexts[0];
            tvCurveType2.setText(string);
            List<String> list = deviationCurveDataList.get(0);
            deviationCurveList.clear();
            deviationCurveList.addAll(list);
            setLineChart(llLineChart2, false, list);

        }

    }


    /**
     * @param type
     * @param texts        显示数据
     * @param textView
     * @param linearLayout
     * @param list
     */
    private void showPopupView(int type, String[] texts, TextView textView, LinearLayout linearLayout, List<List<String>> list) {
        if (null == texts)
            return;

        new XPopup.Builder(mContext)
                .hasShadowBg(true)
                .maxHeight((int) (ScreenUtils.getScreenHeight() * .5f))
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asBottomList("请选择一项", texts,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                List<String> list1 = list.get(position);
                                boolean mIsMax = false;
                                if (type == 0) {//电量曲线
                                    curveList.clear();
                                    curveList.addAll(list1);
                                    mIsMax = true;
                                }
                                if (type == 1) {//偏差曲线
                                    deviationCurveList.clear();
                                    deviationCurveList.addAll(list1);
                                    mIsMax = false;
                                }

                                textView.setText(text);
                                setLineChart(linearLayout, mIsMax, list1);
                            }
                        }).show();


    }


    private void setLineChart(LinearLayout llLineChart, boolean mIsMax, List<String> list) {
        llLineChart.removeAllViews();
        llLineChart.addView(new LineChartView(mContext, list, 2,mIsMax, true));
    }


    private void setNullView(LinearLayout llLineChart) {
        llLineChart.removeAllViews();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                70);
        TextView textview = new TextView(this);
        textview.setText("暂无数据");
        textview.setGravity(Gravity.CENTER);
        textview.setLayoutParams(layoutParams);
        textview.setTextSize(12);

        llLineChart.addView(textview);
    }

}